package com.trainsmart.smartmvc
{
	import flash.display.DisplayObjectContainer;
	import flash.utils.Dictionary;
	
	import mx.core.UIComponent;
	
	public class ContextManager
	{
		private var contexts:Array = new Array();
		
		private static var instance:ContextManager = new ContextManager();
		
		public var cache:Dictionary = new Dictionary();
		
		public function ContextManager()
		{
		}
		
		public static function getInstance():ContextManager
		{
			return instance;
		}
		
		public function registerContext(context:Context):void{
			contexts[context.getContextId()] =  context;
		}
		
		public function unRegisterContext(contextId:Number):void
		{
			contexts[contextId] = null;	
		}
		public function getAllContexts():Array
		{
			var array:Array = new Array();
			for each(var c:Context in contexts){
				if(c!=null){
					array.push(c);	
				}
			}	
			return array;
		}
		
		public  function findout(ui:UIComponent):Context
		{
			var contexts:Array = getAllContexts();
			var found:Context = null;
			var parent:DisplayObjectContainer = ui;
			while(parent!=null){
				for(var i:int=0;i<contexts.length;i++){
					var context:Context = contexts[i] as  Context;
					var root:UIComponent = context.attachUI;
					if(root==parent){
						found = context;
						parent=null;
						break;
					}
				}
				if(parent!=null)
					parent=parent.parent;
			}
			return found;
		}
	}
}